import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/GlobalData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///我的页控制器
class MyController extends BaseController {
  //数据
  Map<String, dynamic> data = {};

  Map<String, dynamic> vipInfo = {};

  RefreshController baseRefreshCtr = RefreshController(initialRefresh: false);

  @override
  void onInit() {
    EventMgr.on(EventType.refreshLogin, (arg) async {
      print('是否触发事件');
      onPageRefreshData();
    });

    EventMgr.on(EventType.refreshOrderList, (arg) async {
      onPageRefreshData();
    });

    EventMgr.on(EventType.refreshLogout, (arg) async {
      data = {};
      vipInfo = {};
    });

    onPageRefreshData();
    super.onInit();
  }

  void getUserInfo() {
    Tools.showLoading();
    Network.getUserInfo().then((value) {
      AppData.sid = value['sid'];
      GlobalData.sid = value['sid'];
      AppData.mid = value['mid'];
      AppData.uid = value['uid'];
      AppData.avatar = value['avatar'];
      AppData.nickname = value['nickname'];
      AppData.phoneNumber = value['mobile'];
      AppData.isOpnRecommendConfig = (value['recommendConfig'] ?? 0) != 0;
      update();
      Tools.hideLoading();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  void getMineData() {
    Tools.showLoading();
    Network.getMine().then((value) {
      data = value;
      update();
      Tools.hideLoading();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///获取会员信息
  Future getVipInfo() async {
    Tools.showLoading();
    return Network.getVipInfo({}).then((value) {
      vipInfo = value;
      update();
      Tools.hideLoading();
    }).catchError((onError) {
      print(onError);
      Tools.hideLoading();
    });
  }

  //刷新数据
  void onPageRefreshData() {
    if (AppData.isLogin) {
      getUserInfo();
      getMineData();
      getVipInfo();
    }
  }

  @override
  onPageRefresh() async {
    super.onPageRefresh();
    onPageRefreshData();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onClose() {
    EventMgr.off(EventType.refreshLogin);
    EventMgr.off(EventType.refreshOrderList);
    EventMgr.off(EventType.refreshLogout);
    super.onClose();
  }
}
